<?php
/**
 *
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2019-01-18
 * Time: 14:06
 */

namespace App\Http\Controllers\Api\V1\Front;


use App\Http\Controllers\Controller;
use App\Libs\Contracts\PayMent\Wxpay\JsApiNativePay;
use App\Models\GiftCommodity;
use App\Models\UserRecharge;
use App\Services\Front\UserScoreService;
use Illuminate\Http\Request;

class RechargeController extends Controller
{
    public function index(Request $request)
    {
        $rechargeList[0]['rechargeMoney'] = 1;
        $rechargeList[0]['commodityList'] = GiftCommodity::where('grade', 2)->where('stock', '>', 0)->get()->toArray();

        $rechargeList[1]['rechargeMoney'] = 99900;
        $rechargeList[1]['commodityList'] = GiftCommodity::where('grade', 3)->where('stock', '>', 0)->get()->toArray();

        $rechargeList[2]['rechargeMoney'] = 999900;
        $rechargeList[2]['commodityList'] = GiftCommodity::where('grade', 4)->where('stock', '>', 0)->get()->toArray();

        $rechargeList[3]['rechargeMoney'] = 9999900;
        $rechargeList[3]['commodityList'] = GiftCommodity::where('grade', 5)->where('stock', '>', 0)->get()->toArray();

        return $this->apiResponse($rechargeList);

    }

    public function recharge(Request $request)
    {
        $openid = $request->openId;
        $userId = $request->USERID;
        $money = $request->rechargeMoney;
        $status = $request->status;
        $data = [];
        $data['orderNo'] = orderNo();
        $data['userId'] = $userId;
        $data['totalPrice'] = $money;
        $data['rechargeStatus'] = 0;
        $data['createTime'] = date('Y-m-d H:i:s', time());
        $data['status'] = $status;

        //微信支付返回preId
        $orderDetail['orderNo'] = $data['orderNo'];
        $orderDetail['totalPrice'] = $money;
        $orderDetail['body'] = "充值";
        $orderDetail['openId'] = $openid;
        $orderDetail['notifyUrl'] = env('RECHARGE_NOTIFY_URL');
        $result = JsApiNativePay::JsApiNativePay($orderDetail);

        //再次签名，给前端返回
        $timestamp = time();
        $signType = "MD5";
        $package = 'prepay_id=' . $result['prepay_id'];
        $nonceStr = nonceStr();
        $resSignRaw = "appId=" . env("APPID") . "&nonceStr=" . $nonceStr . "&package=" . $package . "&signType=" . $signType . "&timeStamp=" . $timestamp . "&key=" . env("WX_KEY");
        $resSign = md5($resSignRaw);
        $responseOrder['appId'] = env("APPID");
        $responseOrder['package'] = $package;
        $responseOrder['paySign'] = $resSign;
        $responseOrder['nonceStr'] = $nonceStr;
        $responseOrder['signType'] = $signType;
        $responseOrder['timeStamp'] = $timestamp;
        $responseOrder['orderNo'] =  $data['orderNo'];
        $status = UserRecharge::create($data);
        if (!$status) {
            return $this->apiResponse('', config('errorCode.ORDER_FAILS'));
        }
        return $this->apiResponse($responseOrder);
    }
}